{% extends 'sales/base.html' %}
{% load static %}
{% block breadcrumb %}
<nav aria-label="breadcrumb">
  <ol class="breadcrumb">
    <li class="breadcrumb-item"><a href="{% url 'leads:list' %}">Leads</a></li>
    <li class="breadcrumb-item active">{% if lead_obj %}Edit{% else %}Create{% endif %}</li>
  </ol>
</nav>
{% endblock %}
{%block content%}

<head>
  <link rel="stylesheet" type="text/css"
    href="//ajax.googleapis.com/ajax/libs/jqueryui/1.8.13/themes/start/jquery-ui.css" />
</head>
<form id="lead_form" method="POST" action="" novalidate enctype="multipart/form-data">
  <div class="overview_form_block row marl justify-content-center">
    <div class="col-md-9">
      <div class="card">
        <div class="card-body">
          <div class="card-title text-center">
            {% if lead_obj %}EDIT{% else %}CREATE{% endif %} LEAD
          </div>
          <div class="row marl no-gutters">
            <div class="col-md-4">
              <div class="filter_col col-md-12">
                <div class="form-group">
                  <div class="row">
                    <div class="filter_col col-md-6">
                      <label for="exampleInputEmail1" class="name">First
                        Name{% if lead_form.first_name.field.required %}<span class="error">*</span>{% endif %}</label>
                      {{ lead_form.first_name }}
                      <span class="error error_message"
                        id="error_id_first_name">{{ lead_form.first_name.errors }}</span>
                    </div>
                    <div class="filter_col col-md-6">
                      <label for="exampleInputEmail1" class="name">Last
                        Name{% if lead_form.last_name.field.required %}<span class="error">*</span>{% endif %}</label>
                      {{ lead_form.last_name }}
                      <span class="error error_message" id="error_id_last_name">{{ lead_form.last_name.errors }}</span>
                    </div>
                  </div>
                </div>
              </div>
              <div class="filter_col col-md-12">
                <div class="form-group">
                  <label for="exampleInputEmail1" {% if request.POST.status == "converted" %} class="required"
                    {% endif %}>Account Name{% if lead_form.account_name.field.required %}<span
                      class="error">*</span>{% endif %}</label>
                  {{ lead_form.account_name }}
                  <span class="error error_message"
                    id="error_id_account_name">{{ lead_form.account_name.errors }}</span>
                  {% if error %}
                  <span class="error error_message" id="error_id_}">{{ error }}</span>
                  {% endif %}
                </div>
              </div>
              <div class="filter_col col-md-12">
                <div class="form-group">
                  <label for="exampleInputEmail1">Title{% if lead_form.title.field.required %}<span
                      class="error">*</span>{% endif %}</label>
                  {{ lead_form.title }}
                  <span class="error error_message" id="error_id_title">{{ lead_form.title.errors }}</span>
                </div>
              </div>
              <div class="filter_col col-md-12">
                <div class="form-group ">
                  <label for="exampleInputEmail1">Phone{% if lead_form.phone.field.required %}<span
                      class="error">*</span>{% endif %}</label>
                  <input type="tel" name="phone"
                    value="{% if lead_obj and lead_obj.phone_raw_input %}{{lead_obj.phone}}{% endif %}"
                    class="form-control" placeholder="+911234567890" id="id_phone">
                  <span class="error error_message" id="error_id_phone">{{ lead_form.phone.errors }}</span>
                </div>
              </div>
              <div class="filter_col col-md-12">
                <div class="form-group ">
                  <label for="exampleInputEmail1" class="required">Email
                    Address{% if lead_form.email.field.required %}<span class="error">*</span>{% endif %}</label>
                  {{ lead_form.email }}
                  <span class="error error_message" id="error_id_email">{{ lead_form.email.errors }}</span>
                  {% if error %}
                  <span class="error error_message" id="error_id_}">{{ error }}</span>
                  {% endif %}
                </div>
              </div>

              <div class="filter_col col-md-12">
                <div class="form-group">
                  <label for="exampleInputEmail1">Attachment</label>
                  <input type="file" name="lead_attachment" id="lead_attachment">
                  {% if lead_obj.lead_attachment.count %}
                  {% for attachment in lead_obj.lead_attachment.all %}
                  <div id="attachment{{attachment.id}}" class="mt-2">
                    <a target="_blank" href="{{ attachment.attachment.url }}">{{ attachment.file_name }}</a>
                    {% if not attachment.created_by.role == 'ADMIN' or attachment.created_by.role == request.user.role %}
                    <a class="action btn primary_btn" onclick="remove_attachment({{attachment.id}})">X</a>
                    {% endif %}
                  </div>
                  {% endfor %}
                  {% endif %}
                  <span class="error"></span>
                </div>
              </div>
            </div>
            <div class="col-md-4">
              <div class="filter_col col-md-12">
                <div class="form-group">
                  <label for="exampleInputEmail1">Website{% if lead_form.website.field.required %}<span
                      class="error">*</span>{% endif %}</label>
                  {{ lead_form.website }}
                  <span class="error error_message" id="error_id_website">{{ lead_form.website.errors }}</span>
                </div>
              </div>
              <div class="filter_col col-md-12">
                <div class="form-group">
                  <label for="exampleInputEmail1">Description{% if lead_form.description.field.required %}<span
                      class="error">*</span>{% endif %}</label>
                  {{ lead_form.description }}
                  <span class="error error_message" id="error_id_description">{{ lead_form.description.errors }}</span>
                </div>
              </div>
              {% if request.user.is_superuser or request.user.role == 'ADMIN' %}
              <div class="filter_col col-12">
                <div class="form-group">
                  <label for="id_sattus">Teams{% if lead_form.teams.field.required %}<span
                      class="error">*</span>{% endif %}</label>
                  <select name="teams" id="id_teams" class="assigned_users form-control" multiple>
                    {% for team in teams %}
                    <option data-users="{{team.get_users}}" value="{{team.id}}" {% if team in lead_obj.teams.all %}
                      selected="" {% endif %}>
                      {{team}}</option>
                    {% endfor %}
                  </select>
                  <span class="error" id="id__teams">{{ lead_form.teams.errors }}</span>
                </div>
              </div>

              <div class="filter_col col-12">
                <div class="form-group">
                  <label for="id_sattus"><span class="">Users</span></label>
                  <select name="" aria-readonly="true" id="_id_assigned_to" class=" form-control" multiple>
                    {% if lead_obj and lead_obj.teams.all %}
                    {% for user in users %}
                    {% if user in lead_obj.get_team_users %}
                    <option value="{{user.id}}" selected="">{{user.email}}</option>
                    {% else %}
                    <option value="{{user.id}}">{{user.email}}</option>
                    {% endif %}
                    {% endfor %}
                    {% else %}
                    {% for user in users %}
                    <option value="{{user.id}}">{{user.email}}</option>
                    {% endfor %}
                    {% endif %}
                  </select>
                </div>
              </div>

              {% endif %}
              <div class="filter_col col-md-12">
                <div class="form-group">
                  <label for="exampleInputEmail1">Assigned Users</label>
                  <select class="assigned_users form-control" name="assigned_to" multiple="multiple"
                    id="id_assigned_to">
                    {% for user in users %}
                    <option value="{{user.id}}" {% if user in lead_obj.get_assigned_users_not_in_teams or user.id in assignedto_list %}
                      selected="" {% endif %}>{{user.email}}</option>
                    {% endfor %}
                  </select>
                  <span class="error error_message" id="error_id_assigned_to">{{ lead_form.assigned_to.errors }}</span>
                </div>
              </div>
            </div>
            <div class="col-md-4">
              <div class="filter_col col-md-12">
                <div class="form-group">
                  <label for="exampleInputEmail1">Status{% if lead_form.status.field.required %}<span
                      class="error">*</span>{% endif %}</label>
                  {{ lead_form.status }}
                  <span class="error error_message" id="error_id_status">{{ lead_form.status.errors }}</span>
                </div>
              </div>
              <div class="filter_col col-md-12">
                <div class="form-group">
                  <label for="exampleInputEmail1">Source{% if lead_form.source.field.required %}<span
                      class="error">*</span>{% endif %}</label>
                  {{ lead_form.source }}
                  <span class="error error_message" id="error_id_source">{{ lead_form.source.errors }}</span>
                </div>
              </div>
              <div class="filter_col col-md-12">
                <div class="form-group">
                  <label for="exampleInputEmail1">Address</label>
                  {{ lead_form.address_line }}
                  <span class="error error_message"
                    id="error_id_address_line">{{ lead_form.address_line.errors }}</span>
                </div>
                {{ lead_form.street }}
                <span class="error error_message" id="error_id_street">{{ lead_form.street.errors }}</span>
                <div class="row" style="margin-top:10px;">
                  <div class="col-md-4">
                    {{ lead_form.city }}
                    <span class="error error_message" id="error_id_city">{{ lead_form.city.errors }}</span>
                  </div>
                  <div class="col-md-4">
                    {{ lead_form.state }}
                    <span class="error error_message" id="error_id_state">{{ lead_form.state.errors }}</span>
                  </div>

                  <div class="col-md-4">
                    {{ lead_form.postcode }}
                    <span class="error error_message" id="error_id_postcode">{{ lead_form.postcode.errors }}</span>
                  </div>
                  <div class="col-md-12" style="margin-top:10px;">
                    {{ lead_form.country }}
                    <span class="error error_message" id="error_id_country">{{ lead_form.country.errors }}</span>
                  </div>
                </div>
              </div>
              <br>
              <div class="filter_col col-12">
                <div class="form-group">
                  <label>Tags</label>
                  <div class="txt-box-div" id="tag-div"><input type="text" name="tags" id="tags_1"
                      value="{% for t in lead_obj.tags.all %}{{t.name}}, {% endfor %}" class="tags" />
                  </div>
                </div>
              </div>
            </div>
            <div class="col-md-12">
              <div class="row marl buttons_row text-center form_btn_row">
                <button class="btn btn-default save" type="submit" id="submit_btn">Save</button>
                {% if not lead_obj %}
                <button class="btn btn-success save savenew" type="submit">Save & New</button>
                {% endif %}
                <a href="{% url 'leads:list' %}" class="btn btn-default clear" id="create_lead_cancel">Cancel</a>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
    <input type="hidden" id="save_new_form" name="savenewform">
  </div>
</form>
<div class="row marl justify-content-center text-center mt-5 mb-5" id="progress_bar">
  
  <div class="progress position-relative" style="width:40%;height:1.5rem;">
    <span class="justify-content-center d-flex position-absolute w-100 percent">0%</span>
    <div class="progress-bar bar"></div>
  </div>
</div>
{% endblock %}
{% block js_block %}
<script type="text/javascript">

  var bar = $('.bar');
  var percent = $('.percent');

  $('#_id_assigned_to').select2({ disabled: 'readonly' });


  $('#progress_bar').hide()

  $('form#lead_form').ajaxForm({
    type: 'POST',
    dataType: 'json',
    url: ".",
    data: $('#lead_form').serialize(),
    beforeSubmit: disableButton,
    beforeSend: function () {
      var percentVal = '0%';
      bar.width(percentVal);
      percent.html(percentVal);
    },
    uploadProgress: function (event, position, total, percentComplete) {
      var percentVal = percentComplete + '%';
      bar.width(percentVal);
      if (percentVal == '100%') {
        percent.html('Uploading ...')
      }
      else {
        percent.html(percentVal);
      }
    },
    success: function (data) {
      if (data.error) {
        $('#progress_bar').hide()
        $('.error_message').html('')
        for (var key in data.errors) {
          $('#error_id_' + key).html("<p>" + data.errors[key][0] + "</p>");
        };
        $('#submit_btn').removeAttr('disabled')
      }
      else {
        window.location = data.success_url;
      }
    }
  });


  $('#submit_btn').click(function () {
    var file = $('#lead_attachment')[0].files[0];
    if (file && file.name.length > 0) {
      var percentVal = '0%';
      bar.width(percentVal);
      percent.html(percentVal);
      $('#progress_bar').show()
    }

  });

  function disableButton() {
    // $('#progress_bar').show()
    console.log($('#lead_form').serialize())
    $('#submit_btn').attr('disabled', 'disabled')
  }

  $(".savenew").on('click', function (e) {
    e.preventDefault()
    $("#save_new_form").val('true')
    $('#lead_form').submit()
  });
  $(document).ready(function () {
    $('.assigned_users').select2();
    $('#id_teams').select2();

  });
  $(function () {

    $('#tags_1').tagsInput({ width: 'auto' });
    $('#tags_2').tagsInput({
      width: 'auto',
      onChange: function (elem, elem_tags) {
        var languages = ['php', 'ruby', 'javascript'];
        $('.tag', elem_tags).each(function () {
          if ($(this).text().search(new RegExp('\\b(' + languages.join('|') + ')\\b')) >= 0)
            $(this).css('background-color', 'yellow');
        });
      }
    });
    $('#tags_3').tagsInput({
      width: 'auto',

      //autocomplete_url:'test/fake_plaintext_endpoint.html' //jquery.autocomplete (not jquery ui)
      autocomplete_url: 'test/fake_json_endpoint.html' // jquery ui autocomplete requires a json endpoint
    });


    // Uncomment this line to see the callback functions in action
    //      $('input.tags').tagsInput({onAddTag:onAddTag,onRemoveTag:onRemoveTag,onChange: onChangeTag});   

    // Uncomment this line to see an input with no interface for adding new tags.
    //      $('input.tags').tagsInput({interactive:false});
  });

  function remove_attachment(x) {
    const con = confirm("Do you want to Delete it for Sure!?");
    if (con == true) {
      $.post('{% url "cases:remove_attachment" %}', {
        "attachment_id": x
      }, function (data) {
        if (data.error) {
          alert(data.errors)
        } else {
          $("#attachment" + data.attachment_object).remove()
        }
      })
    }
  }

  function find_dict(dict, id){
    var index = dict.map(function(o) { return o.team; }).indexOf(parseInt(id));
    return dict[index]['users']
  }

  $("#id_teams").change(function (e) {
    var teams = []
    var all_users = []
    var selected_teams = []
    var selected_users = []
    var assigned_users = []
    $.get("{% url 'leads:get_teams_and_users' %}", function(data){
      // console.log(data)
          if(($('#id_teams').val()).length==0){
            $('#id_assigned_to option').each(function () {
            $(this).removeAttr('disabled')
            })
        $('#id_assigned_to').select2().trigger('change');

          }

      teams = data['teams']
      all_users = data['users']
      try {
        var users = []
        $('#id_teams option:selected').each(function () {
          // users.push($(this).attr('data-users'))
          _data = $(this).attr('data-users');
          selected_teams.push($(this).val())
          selected_users.push(find_dict(teams, $(this).val()))
          // console.log("s_users", selected_users)
          var un_select_users = [].concat.apply([], selected_users)
          // console.log('un select users', un_select_users);


        $('#id_assigned_to option').each(function () {
          if($.inArray(parseInt($(this).val()), un_select_users) != -1){
            $(this).attr('disabled', 'disabled')
            $('#id_assigned_to').select2();

          }
          else{
            $(this).show()
            $(this).removeAttr('disabled')
            $('#id_assigned_to').select2();

          }
          }
        )


          if (!selected_teams) {
            users = []
            $('#id_assigned_to option').each(function () {
            $(this).removeAttr('disabled')
            })
            $('#id_assigned_to').select2();
          } else {
            users = users.concat(_data.split(','))
          }
        });
        $('#id_teams option').each(function () {
          if ($(this).is(':selected')) {
            _data = $(this).attr('data-users').split(',')
            // console.log(' selected', $(this).attr('data-users').split(','))
            // console.log('selected', $(this).attr('data-users'))
          }
          else {
            _unselected = $(this).attr('data-users').split(',')
            // console.log('un selected', $(this).attr('data-users').split(','))
          }
        });
        // console.log('selected users teams data', users)
        var existingUsers = $('#id_assigned_to').val();
        var allUsers = users
        $('#_id_assigned_to').select2().val(allUsers).trigger('change');
        $('#id_assigned_to').select2().val(existingUsers).trigger('change');
        if (users.length) {

        }
      } catch (error) {
        console.log(error)
        $('#_id_assigned_to').select2().val([]).trigger('change');
      }
    })

  });

  $(document).ready(function($) {
    
    var teams = []
    var all_users = []
    var selected_teams = []
    var selected_users = []
    var assigned_users = []
    $.get("{% url 'leads:get_teams_and_users' %}", function(data){

          if(($('#id_teams').val()).length==0){
            $('#id_assigned_to option').each(function () {
            $(this).removeAttr('disabled')
            })
        // $('#id_assigned_to').select2().val([]).trigger('change');

          }

      teams = data['teams']
      all_users = data['users']
      try {
        var users = []
        $('#id_teams option:selected').each(function () {
          // users.push($(this).attr('data-users'))
          _data = $(this).attr('data-users');
          selected_teams.push($(this).val())
          selected_users.push(find_dict(teams, $(this).val()))
          var un_select_users = [].concat.apply([], selected_users)


        $('#id_assigned_to option').each(function () {
          if($.inArray(parseInt($(this).val()), un_select_users) != -1){
            // $(this).attr('disabled', 'disabled')
            $(this).attr('disabled', 'disabled')
            $('#id_assigned_to').select2();

          }
          else{
            $(this).show()
            $(this).removeAttr('disabled')
            $('#id_assigned_to').select2();

          }
          }
        )


          if (!selected_teams) {
            users = []
            $('#id_assigned_to option').each(function () {
            $(this).removeAttr('disabled')
            })
            $('#id_assigned_to').select2();
          } else {
            users = users.concat(_data.split(','))
          }
        });
        $('#id_teams option').each(function () {
          if ($(this).is(':selected')) {
            _data = $(this).attr('data-users').split(',')
          }
          else {
            _unselected = $(this).attr('data-users').split(',')
          }
        });
        var existingUsers = $('#id_assigned_to').val();
        // var allUsers = users.concat(existingUsers)
        var allUsers = users
        // console.log(existingUsers)
        $('#_id_assigned_to').select2().val(allUsers).trigger('change');
        if (users.length) {

        }
      } catch (error) {
        console.log(error)
        $('#_id_assigned_to').select2().val([]).trigger('change');
      }
    })

  });
</script>
{% endblock js_block %}